<?php
/*
XtraUpload - File Hosting Software
Copyright (C) 2006-2007  Matthew Glinski and XtraFile.com
Link: http://www.xtrafile.com
-----------------------------------------------------------------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program(LICENSE.txt); if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

function detect_browser($var)
{
		if(eregi("(msie) ([0-9]{1,2}.[0-9]{1,3})", $var)) 
		{
			$c = "ie"; 
		}else{
			$c = "nn"; 
		}
	return $c;
}

function downloadFail($file,$name,$totaldownload,$fileSize,$limit_speed,$dlid)
{
	global $kernel, $db, $dlComplete;
	if(!$dlComplete)
	{
		log_action('File Downloaded:('.$name.') ', 'file:download', 'File('.$file.') was downloaded by '.$_SERVER['REMOTE_ADDR'].'', 'ok', 'download.php');
		$bw = $kernel->ext->download->bandwith;
		if (!($limit != '0' && ($totaldownload + $fileSize >= ($_SESSION['d_limit'] * 1024 * 1024))))  
		{
			$db->query('INSERT INTO downloads (ip,filesize,filename,time) VALUES ("' . $_SERVER['REMOTE_ADDR'] . '", "' . $bw . '", "' . $fileToDownload . '", UNIX_TIMESTAMP())');
		}
		update_bandwith($name,$bw);
		$db->query("DELETE FROM `dlsessions` WHERE `id` = '".$dlid."'");
	}
	die();
}

function doDirectDownload($link)
{
	global $db, $kernel, $siteurl, $rewrite_links, $lang, $siteurl, $myuid, $downloadLimit;
	
	$limit_speed = getSpeedFromLink($link);

	// Get Current dLink Stuff
	$q = $db->query("SELECT * FROM `dlinks` WHERE `down_id` = '".intval($link)."' ");

    /* Start by making sure the file link actually exists */
    if((int)$db->num($q) > 0)
    {
		$res = $db->fetch($q,'obj');
		$q1 = $db->query("SELECT * FROM files WHERE filename = '".$res->store_name."' ");
		$res1 = $db->fetch($q1,'obj');


		// Localize Vars
		$md5 = $res1->md5;
		$fileToDownload = $res->store_name;
		$hash = $res->hash;
		$orig_filename = $res->real_name;
		$ip = $res->resume;
		$resume = $res->can_r;
		$limit = intval($downloadLimit);
		$_SESSION['file_name'] = $res1->o_filename;
		
		// I Can Steal Cheezburger? -NO!!!
		if ($ip != $_SERVER['REMOTE_ADDR']) 
		{
			header('Location: '.$siteurl.'index.php?p=download&hash='.$res1->hash);
			die();
		}
		
		// Terminate if download threads over limit
		$dlse = 0;
		$dls = $db->query("SELECT * FROM `dlsessions` WHERE `file` = '" . intval($_GET['link'])."' AND `ip` = '".$_SERVER['REMOTE_ADDR']."'");  
		$dlse = $db->num($dls);
		
		if($dlse >= $res->limit and $res->limit != 0)
		{
			header('Status: 416');
			$dlf = $db->fetch($dls);
			echo "Download Failure:  Thread Limit Reached, <br />Threads used: ".$dlse."<br /> Threads allowed: ".$res->limit;
			downloadFail('./files/'.substr($md5,0,2).'/'.$fileToDownload,$orig_filename,$totaldownload,$fileSize,$limit_speed,$dlid);
			exit();
		}
		
		// Make new thread
		$db->query("INSERT INTO `dlsessions` (`file`, `ip`) VALUES ('".$link."', '".$_SERVER['REMOTE_ADDR']."')");
		$dlid = $db->insert_id();
		
		/* Check if user has exceeded limit */
		$totaldownload = 0;
		$db->query("DELETE FROM `dlinks` WHERE `time` > (UNIX_TIMESTAMP() + 3600)");
		$tD = $db->query("SELECT `filesize` FROM `downloads` WHERE `ip` = '".$_SERVER['REMOTE_ADDR']."'");
		while($dlTotal = $db->fetch($tD))
		{
			$totaldownload += intval($dlTotal->filesize);
		}
		
		if (($limit != 0) && ($totaldownload >= ($limit * 1024 * 1024))) 
		{
			header('Location: '.makeXuLink('index.php','p=errordl'));
			die();
		}

		/* Read in the original file and present dialog to user */
		$limit_speed = intval($limit_speed);
		
		/**
		* If your web server has output compression enabled 
		* (quite common) this needs to be disabled in order 
		* for MSIE to obey our Content Disposition header 
		*/
        if(ini_get('zlib.output_compression'))
		{
			ini_set('zlib.output_compression', 'Off');
		}
		
		// Download system class under $kernel->ext->download
		$kernel->loadUserExt('download');
		
		// Function to call if user aborts connection
		register_shutdown_function('downloadFail','./files/'.substr($md5,0,2).'/'.$fileToDownload,$orig_filename,$totaldownload,$fileSize,$limit_speed,$dlid);

		$ok = $kernel->ext->download->set_byfile('./files/'.substr($md5,0,2).'/'.$fileToDownload); //Download from php data
		if(!$ok)
		{
			header('Location: '.$siteurl.'index.php?p=fileError&hash='.$res1->hash);
			die();
		}
		
		$kernel->ext->download->use_resume = ((bool)$res->can_r); //Enable Resume Mode
		$kernel->ext->download->filename = $orig_filename;
		
		if($limit_speed > 0)
		{
			$kernel->ext->download->speed = ((int)$limit_speed);
		}
		else
		{
			$kernel->ext->download->speed = 0;
		}
		
		$bw = $kernel->ext->download->sendDownload(); //Download File
			
		$_SESSION['file_size'] = round($bw/1024,2);
		$db->query('INSERT INTO `downloads` (`ip`,`filesize`,`filename`,`time`) VALUES ("' . $_SERVER['REMOTE_ADDR'] . '", "' . $bw . '", "' . $fileToDownload . '", UNIX_TIMESTAMP())');
		$ret = update_bandwith($fileToDownload,$bw);
		$dlComplete = true;

		if(intval($myuid) > 0)
		{
			add_points_download($_SESSION['myuid'],$hash);
		}
		
		$db->query("UPDATE `files` SET `downloads` = downloads+1, `last_download` = '".time()."' WHERE `filename` = '".$fileToDownload."' LIMIT 1");
		$db->query("DELETE FROM `dlsessions` WHERE `id` = '".$dlid."'");
	} 
	else 
	{
		header("Location: ".makeXuLink('index.php', 'p=home&nolink=1'));
		die();
	}
}

doDirectDownload($_GET['link']);
?>